﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace Googler
{

    public static class ConfigurationExtenstionMethods
    {
        public static T GetValue<T>(this AppSettingsSection appSettings, string key)
        {
            if (!appSettings.Settings.AllKeys.Contains(key))
                appSettings.Settings.Add(new KeyValueConfigurationElement(key, "True"));

            return (T)Convert.ChangeType(appSettings.Settings[key].Value, typeof(T));
        }

        public static void SetValue(this AppSettingsSection appSettings, string key, string value)
        {
            if (!appSettings.Settings.AllKeys.Contains(key))
                appSettings.Settings.Add(new KeyValueConfigurationElement(key, value));

            appSettings.Settings[key].Value = value;
        }
        public static void SetValue(this ConnectionStringsSection section, string key, string value)
        {
            ConnectionStringSettings connString = null;
            foreach (ConnectionStringSettings item in section.ConnectionStrings)
            {
                if (item.Name == key)
                {
                    connString = item;
                }
            }
            if (connString == null)
            {
                section.ConnectionStrings.Add(new ConnectionStringSettings(key, value));
            }

            section.ConnectionStrings[key].ConnectionString = value;
        }
    }
}
